package com.msh.platform.elm.controller;

import com.msh.platform.bizmedia.base.conf.ResponseResult;
import com.msh.platform.bizmedia.base.util.AliOssTools;
import com.msh.platform.bizmedia.base.util.SessionUtil;
import com.msh.platform.bizmedia.base.vo.AvatarVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Author zhangyangsong
 * @Description :
 * @Date: Created in 2018/11/8
 * @Copyright: ©2018 all rights reserved.
 */
@RestController
@RequestMapping(value = "/upload")
@Api(tags = "文件上传")
public class UploadController {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
    @Autowired
    private AliOssTools aliOssTools;


    @ApiOperation(value = "上传头像")
    @PostMapping(path = "/upload_avatar")
    public ResponseResult<AvatarVO> uploadAvatar(MultipartFile files) {

        if (files == null ) {
            return ResponseResult.fail(-1,"没有接收到图片文件");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("上传文件的参数信息,type:{},filename:{}",files.getContentType(),files.getOriginalFilename());
        }
        String fileName = files.getOriginalFilename();

        if (logger.isDebugEnabled()) {
            logger.debug("session 信息:{]",SessionUtil.getLocalUserInfo());
        }
//        Integer userId = SessionUtil.getLocalUserInfo().getId();
        try {
            String rfilename = this.getClass().getClassLoader().getResource(".").getPath()+fileName;
            File filecopy = new File(rfilename);
            files.transferTo(filecopy);
//            logger.debug("目的文件：{}",filecopy.getName());
            String strUrl = aliOssTools.uploadFile(fileName,filecopy,"avatar");
//            MshUserImage image = new MshUserImage();
//            image.setUserid(userId);
//            image.setType("avatar");
//            image.setUrl(strUrl);
//            mshUserImageRepository.save(image);
            AvatarVO resVO = new AvatarVO();
            resVO.setAvatar(strUrl);
            return ResponseResult.success(resVO);
        } catch (IOException e) {
            logger.error("获取上传文件流异常：",e);
            return ResponseResult.fail(-1,"获取上传文件流异常");
        }
    }
}
